// pages/search/search.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeHolder: '输入你要查找的内容',
    autoFocus: true,
    inputEnable: true,
    keydown_number: 0,
    input_value: "",
  },

  onLoad: function (options) {},
  redictAct: function (event) {
    var id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../detail/detail?id=' + id
    });
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    console.log(e)
    if (e.scrollTop > 70) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
  },

  onInput: function (e) {
    this.setData({
      searchKey: e.detail.value,
    })
    if (this.data.searchKey == "roleadmin") {
      const db = wx.cloud.database()
      db.collection("book_user")
        .where({
          _openid: getApp().globalData.openid
        })
        .update({
          data: {
            role: "管理员"
          },
          success: function () {
            wx.switchTab({
              url: '../mine/mine',
              success: function () {
                wx.showToast({
                  title: '已设为管理员',
                  duration: 2000
                })
              }
            })
          }
        })
    }
    if (e.detail.cursor != 0) {
      this.setData({
        keydown_number: 1
      })
    } else {
      this.setData({
        keydown_number: 0
      })
    }
  },

  formSubmit: function (e) {
    if (this.data.keydown_number == 1) {
      this.setData({
        key: this.data.searchKey
      })
      const db = wx.cloud.database();
      const _ = db.command
      db.collection("book_list")
        .where(_.or([{
            title: db.RegExp({
              regexp: '.*' + this.data.key,
              options: 'i',
            })
          },
          {
            author: db.RegExp({
              regexp: '.*' + this.data.key,
              options: 'i',
            })
          }
        ]))
        .get({
          success: res => {
            this.setData({
              list: res.data,
              booksum: res.data.length,
            })
            if (this.data.list.length == 0) {
              wx.showToast({
                icon: 'none',
                title: '没找到相关书籍',
                duration: 2000
              })
              this.setData({
                bookmsg: false,
              })
            } else {
              this.setData({
                bookmsg: true,
              })
            }
          },
          fail: err => {
            console.log(err)
          }
        })
    } else {
      wx.showModal({
        title: '提示',
        content: '请输入内容',
        showCancel: false,
      });
    }
  },
  onClear: function () {
    this.setData({
      searchKey: '',
      bookmsg: false
    })

  },

})